package lightswitch.server.code.sqlhelper.expression;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lightswitch.server.code.sqlhelper.statement.select.From;
import lightswitch.server.code.util.StringHelper;

public class Column {
	public String name="";
	public String type;
	public String alias="";
	public AbstractTable table;
	public Column(String statement, From _from)
	{
	//	statement = statement.substring(1);
	
	//	Pattern p = Pattern.compile("(((.+).[\\.](.+))|(.[^/.]*))");
		if(statement.equals("*"))
		{
			name ="*";
			table = new NormalTable();
			table.alias="*";
			table.name="*";
			
			return ;
		}
		statement = StringHelper.NormalizeString(statement);
		String[] strList = statement.split(" ");
		if(strList.length ==2)
		{
			statement = strList[0];
			alias = strList[1];
		}
		else
		{
			if(strList.length==3 && strList[1].equals("as"))
			{
				statement = strList[0];
				alias = strList[2];
			}
			else
			{
				if(strList.length>3)
				{
					//throw exception
					return;
				}
			}
		}

		if(!statement.contains("."))
		{
			if(_from._tableList.size()==1)
			{
				statement=  _from._tableList.get(0).alias + "."+ statement;
			}
			else
			{
				
				//throw exception
				return;
			}
		}

		statement  = StringHelper.NormalizeString(statement);
		Pattern p = Pattern.compile("^(((?!.*[\\.].*).+)|((?=.+[\\.].+)[A-Za-z0-9. ]+))$");
		Matcher m = p.matcher(statement);

			if (m.find()) {
				if(m.group(2)!=null)
				{
					//String t = m.group(2);
					name = m.group(2);
				}
				else
				{
					if(m.group(3)!=null)
					{
					//	String t = m.group(3);
						String tem = m.group(3);
						String[] att = tem.split("\\.");
						table = new NormalTable();
						table.name=att[0];
					table.alias =att[0];
					name = att[1];
						
					}
				}
			}
			else
			{
				//throw exception
				return;
			}
			
			if(alias.equals(""))
			{
				alias=name;
			}
			
			
			
	}
	public String toString()
	{
		String t="( ";
		if(table!=null)
		{
			t=t+table.alias+".";

		}
		t=t+name+")";
		
		return t;
	}
}
